<template>
  <el-card class="m-8">
    <section>
      <section slot="header" class="mb-4 flex items-center">

        <p class="ml-10">商品名称： </p>
        <el-input v-model="dataForm.gift_name" placeholder="请输入商品名称"></el-input>

        <p class="ml-10">状态：</p>
        <el-select v-model="dataForm.is_open" placeholder="请选择">
          <el-option
            v-for="item in statusOptions"
            :key="item.val"
            :label="item.name"
            :value="item.val"
          >
          </el-option>
        </el-select>


        <el-button class="mr-4" type="info" @click="handleReset();initData()">重置</el-button>
        <el-button class="mr-4" type="primary" @click="dataForm.page=1;initData()">搜索</el-button>

      </section>

      <section slot="header" class="mt-10 flex items-center">
        <el-button class="mr-4" type="primary" @click="addIndepUser">添加商品</el-button>

      </section>

      <el-table :data="tableList" align="center" border class="mt-4" stripe>
        <el-table-column label="商品ID" prop="reward.id"/>
        <el-table-column label="商品图标" prop="reward">
          <template slot-scope="{row}">
            <el-popover
              v-if="row.reward"
              max-width="420"
              placement="left"
              style="margin-right:10px"
              trigger="hover"
            >
              <img
                :src="row.reward.picture"
                alt=""
                style="max-width:200px;max-height:200px"
              />
              <img
                slot="reference"
                :src="row.reward.picture"
                alt=""
                style="width: 100px;"
              />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="reward.title"/>
        <el-table-column label="价格" prop="reward_price"/>
        <el-table-column label="排序" prop="reward_sort"/>
        <el-table-column label="状态" prop="status">
          <template slot-scope="{row}">
            <span v-if="row.status===1">启用</span>
            <span v-else>禁用</span>
          </template>
        </el-table-column>
        <el-table-column label="操作时间" prop="created_at"/>
        <el-table-column align="center" label="操作" width="250">
          <template slot-scope="{row}">
            <el-button class="mr-5" plain @click="addIndepUser(row)">编辑</el-button>
            <el-button
              v-if="row.status !== 1"
              plain
              size="mini"
              type="primary"
              @click="handleChangeStatus(row.id,1)"
            >
              启用
            </el-button>
            <el-button
              v-else
              class="mr-5"
              plain
              size="mini"
              type="danger"
              @click="handleChangeStatus(row.id,0)"
            >禁用
            </el-button
            >
            <el-popconfirm
              cancel-button-text="不用了"
              confirm-button-text="好的"
              icon="el-icon-info"
              icon-color="red"
              title="确定删除吗？"
              @confirm="delRow(row)"
            >
              <el-button slot="reference" type="danger">删除</el-button>
            </el-popconfirm>

          </template>
        </el-table-column>
      </el-table>

      <cus-pagination
        :limit.sync="dataForm.per_page"
        :page.sync="dataForm.page"
        :total="total"
        @pagination="initData"
      />

    </section>


    <el-dialog v-dialogDrag :title="!isEdit?'添加商品':'编辑商品'" :visible.sync="dialogFormVisible"
               @close="handleCloseDialog('addForm')"
    >
      <el-form ref="addForm" :model="dynamicValidateForm" :rules="rules">

        <!--        <el-form-item label="选择商品">-->
        <!--          <el-dropdown>-->
        <!--            <el-button type="primary">-->
        <!--              选择-->
        <!--            </el-button>-->
        <!--            <el-dropdown-menu slot="dropdown">-->
        <!--              <el-dropdown-item @click.native="handleDrop(1)">礼物</el-dropdown-item>-->
        <!--              <el-dropdown-item @click.native="handleDrop(2)">道具</el-dropdown-item>-->
        <!--            </el-dropdown-menu>-->
        <!--          </el-dropdown>-->
        <!--        </el-form-item>-->

        <el-form-item
          label="选择商品"
          prop="reward_type"
        >
          <el-select v-model="dynamicValidateForm.reward_type" placeholder="请选择">
            <el-option
              v-for="item in commodityOptions"
              :key="item.val"
              :label="item.name"
              :value="item.val"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="dynamicValidateForm.reward_type === 1"
          label="选择礼物"
          prop="gift_id"
        >
          <el-select v-model="dynamicValidateForm.gift_id" v-loadMore="loadMore" placeholder="请选择">
            <el-option
              v-for="item in giftOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="dynamicValidateForm.reward_type === 2"
          label="选择道具"
          prop="price_id"
        >
          <el-select v-model="dynamicValidateForm.price_id" placeholder="请选择">
            <el-option
              v-for="item in priceIdOptions"
              :key="item.price_id"
              :label="item.product_name+'('+item.day+')天'"
              :value="item.price_id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!--        <el-form-item-->
        <!--          label="价格类型"-->
        <!--          prop="template_id"-->
        <!--        >-->
        <!--          <el-select v-model="dynamicValidateForm.template_id" placeholder="请选择">-->
        <!--            <el-option-->
        <!--              v-for="item in priceOptions"-->
        <!--              :key="item.val"-->
        <!--              :label="item.name"-->
        <!--              :value="item.val"-->
        <!--            >-->
        <!--            </el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->

        <el-form-item
          label="商品价格"
          prop="reward_price"
        >
          <el-input v-model="dynamicValidateForm.reward_price"></el-input>
        </el-form-item>

        <!--        <el-form-item-->
        <!--          label="限兑规则"-->
        <!--          prop="template_id"-->
        <!--        >-->
        <!--          <el-select v-model="dynamicValidateForm.template_id" placeholder="请选择">-->
        <!--            <el-option-->
        <!--              v-for="item in ruleOptions"-->
        <!--              :key="item.val"-->
        <!--              :label="item.name"-->
        <!--              :value="item.val"-->
        <!--            >-->
        <!--            </el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->

        <el-form-item
          label="限对数量"
          prop="reward_count"
        >
          <el-input v-model="dynamicValidateForm.reward_count"></el-input>
        </el-form-item>

        <el-form-item
          label="排序"
          prop="sort"
        >
          <el-input v-model="dynamicValidateForm.sort"></el-input>
        </el-form-item>

        <el-form-item
          label="状态"
          prop="is_open"
        >
          <el-radio-group v-model="dynamicValidateForm.is_open">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleAddUser('addForm')">保存</el-button>
          <el-button type="danger" @click="dialogFormVisible = false">取消</el-button>
        </span>
    </el-dialog>


    <el-dialog v-dialogDrag :title="!isEdit?'选择礼物':'选择装扮'" :visible.sync="dialogGiftVisible"
               @close="handleCloseDialog('addForm')"
    >

      <div class="flex mt-3">
        <el-input
          v-model="listQuery.gift_name"
          class="mr-4"
          placeholder="请输入礼物名称"
          style="width: 17%"
        ></el-input>
        <el-select
          v-model="listQuery.sale_status"
          placeholder="操作类型"
          style="width: 17%"
        >
          <el-option
            v-for="item in sale_options"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <div class="ml-4 flex items-center" style="width: 17%">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button type="primary" @click="handleResetDetail">刷新</el-button>
        </div>
      </div>

      <el-table :data="menuList" align="center" border class="mt-4" stripe
                @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="礼物图片" prop="picture">
          <template slot-scope="scope">
            <el-popover max-width="420" placement="top" trigger="hover">
              <img
                :src="scope.row.picture"
                alt=""
                style="max-width: 200px; max-height: 200px"
              />
              <img
                slot="reference"
                :src="scope.row.picture"
                alt=""
                style="width: 50px"
              />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="礼物名称" prop="name"></el-table-column>
        <el-table-column label="礼物价值" prop="price"></el-table-column>
        <el-table-column label="创建时间" prop="coin"></el-table-column>
        <el-table-column label="状态" prop="">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.sold === 1" type="primary">上架</el-tag>
            <el-tag v-else type="danger">下架</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <cus-pagination
        :limit.sync="listQuery.page_size"
        :page.sync="listQuery.page"
        :total="total"
        @pagination="handleGetData"
      />

      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleAddUser('addForm')">保存</el-button>
          <el-button type="danger" @click="dialogGiftVisible = false">取消</el-button>
        </span>
    </el-dialog>


  </el-card>
</template>

<script>
import { addOrEditReward, changeBtnReward, delReward, getGiftList, getZbList, giftList } from '../../api/guardActivity'
import { getData } from '@/api/roomGift/giftList'

export default {
  data() {
    return {
      giftOptions: [],
      menuList: [],
      listQuery: {
        gift_name: undefined,
        sale_status: -1,
        page: 1,
        page_size: 10
      },
      sale_options: [
        {
          id: -1,
          title: '全部'
        },
        {
          id: 0,
          title: '下架'
        },
        {
          id: 1,
          title: '上架'
        }
      ],
      multipleSelection: [],
      dialogGiftVisible: false,
      commodityOptions: [
        { val: 1, name: '礼物' },
        { val: 2, name: '道具' }
      ],
      ruleOptions: [
        { val: 0, name: '每日' },
        { val: 1, name: '每周' }
      ],
      priceOptions: [
        { val: 0, name: '金币' },
        { val: 1, name: '能量' }
      ],
      priceIdOptions: [],
      rowId: '',
      tempOptions: [],
      options: [],
      gameId: '',
      hasGame: false,
      isEdit: false,
      dynamicPoolForm: {
        reward_type: '',
        user_id: '',
        template_id: '',
        profit_loss_rate: '',
        is_open: ''
      },
      dialogPoolVisible: false,
      detailFormVisible: false,
      setStatus: 0,
      dialogFormVisible: false,
      dynamicValidateForm: {
        reward_type: '',
        price_id: '',
        gift_id: '',
        reward_price: '',
        reward_count: '',
        sort: '',
        is_open: ''
      },
      rules: {
        reward_price: [{ required: true, message: '请输入', trigger: 'blur' }],
        reward_count: [{ required: true, message: '请输入', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入', trigger: 'blur' }],
        gift_name: [{ required: true, message: '请输入', trigger: 'blur' }],
        gift_id: [{ required: true, message: '请选择', trigger: 'change' }],
        price_id: [{ required: true, message: '请选择', trigger: 'change' }],
        reward_type: [{ required: true, message: '请选择', trigger: 'change' }],

        is_open: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      times: [],
      radio: 1,
      statusOptions: [
        { val: 0, name: '禁用' },
        { val: 1, name: '启用' }
      ],
      setDialogVisible: false,
      tableList: [],
      dateList: undefined,
      dataForm: {
        is_open: '',
        gift_name: '',
        page: 1,
        per_page: 10
      },
      meta: {
        page: 1,
        perPage: 10
      },
      total: 1,
      id: '',
      // 拒绝原因
      setting: {
        balance_coin: 0
      },
      info: '',
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10
    }
  },
  created() {
    this.initData()
    this.initTypeList()
    this.initTypeList2()

  },
  methods: {
    loadMore() {
      if (this.giftOptions.length >= this.sysInstanceTotalPages) return
      this.sysInstanceIndex++
      this.initTypeList()
    },
    async initTypeList() {
      try {
        const { data } = await getGiftList({
          sale_status: -1,
          page: this.sysInstanceIndex,
          page_size: 20
        })
        this.giftOptions = [...this.giftOptions, ...data.data]
        this.sysInstanceTotalPages = data.total
      } catch (e) {

      }
    },

    async initTypeList2() {
      try {
        const { data } = await getZbList({
          status: 1,
          page: 1,
          page_size: 999
        })
        this.priceIdOptions = data.data
      } catch (e) {

      }
    },
    handleResetDetail() {
      this.listQuery = {
        gift_name: undefined,
        sale_status: -1,
        page: 1,
        page_size: 10
      }
      this.handleGetData()
    },
    handleGetData() {
      getData(this.listQuery).then(res => {
        this.menuList = res.data.data
        this.total = res.data.total
      })
    },
    handleSearch() {
      this.listQuery.page = 1
      this.handleGetData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleChangeStatus(id, status) {
      changeBtnReward(id, status).then(res => {
        if (res.code === 200) {
          this.$message.success('操作成功')
          this.initData()
        }
      })
    },
    handleCloseDialog(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate() // 清除整个表单的校验
      }
    },
    async delRow(row) {
      delReward(row.id).then((response) => {
        if (response.code === 200) {
          this.initData()
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        }
      })
    },
    handleSet(row) {
      //todo 设置当前行内容的默认状态
      this.setDialogVisible = true
    },
    handleAddUser(val) {
      this.$refs[val].validate(valid => {
        if (valid) {
          let obj = {}
          for (let key in this.dynamicValidateForm) {
            if (this.dynamicValidateForm[key] !== undefined && this.dynamicValidateForm[key] !== '') {
              obj[key] = this.dynamicValidateForm[key]
            }
          }
          if (!this.isEdit) {
            addOrEditReward(obj).then(res => {
              if (res.code === 200) {
                this.initData()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              }
            })
          } else {
            obj.id = this.rowId
            addOrEditReward(obj).then(res => {
              if (res.code === 200) {
                this.initData()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              }
            })
          }

        } else {
          return false
        }
      })
    },
    addIndepUser(row) {
      if (row.id) {
        this.rowId = row.id
        this.isEdit = true
        // this.info = {
        //   id: row.main_user.user_code,
        //   user: {
        //     rank_id: row.user_base.rank_id
        //   },
        //   input: row.user.total_input,
        //   output: row.user.total_output
        // }
        this.dynamicValidateForm = {
          //todo 改成userCode
          reward_type: row.reward_type,
          price_id: row.reward_mall_id,
          gift_id: row.reward_id,
          reward_price: row.reward_price,
          reward_count: row.reward_count,
          sort: row.reward_sort,
          is_open: row.status
        }
      } else {
        this.dynamicValidateForm = {
          reward_type: '',
          price_id: '',
          gift_id: '',
          reward_price: '',
          reward_count: '',
          sort: '',
          is_open: ''
        }
        this.rowId = ''
        // this.info = ''
        this.isEdit = false
      }
      this.dialogFormVisible = true
    },
    handleReset() {
      this.times = []
      this.dataForm = {
        is_open: '',
        gift_name: '',
        page: 1,
        per_page: 10
      }
    },
    async initData() {
      try {
        const { data } = await giftList(this.dataForm)
        this.tableList = data.data
        this.dataForm.page = data.current_page
        this.total = data.total
      } catch (e) {
        console.error(e)
      }
    }

  }
}
</script>

<style scoped>
.el-input {
  width: 200px;
}

/deep/ .el-table .cell {
  flex-wrap: wrap;
}
</style>
